<template>
  <div class="view-fill">
    <div
      v-show="!assetApplicationDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              @handleEvent="handleEventForm"
            >
              <template v-slot:form-signDeptName>
                <el-input
                  v-model="formInfo.data.signDeptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择签订部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-assetBelongDeptName>
                <el-input
                  v-model="formInfo.data.assetBelongDeptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择资产归口部门"
                >
                  <template #append>
                    <el-icon @click="openAssetBelongDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-signUserName>
                <el-input
                  v-model="formInfo.data.signUserName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择签订人"
                >
                  <template #append>
                    <el-icon @click="openSignUserWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-supplierName>
                <el-input
                  v-model="formInfo.data.supplierName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择供应商"
                >
                  <template #append>
                    <el-icon @click="openSupplierWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div v-show="formInfo.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <p>维保信息</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.repairRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.repairFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>招标信息</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.biddingRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.biddingFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-winBiddingSupplierName>
                <el-input
                  v-model="formInfo.data.winBiddingSupplierName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择供应商"
                >
                  <template #append>
                    <el-icon @click="openwinBiddingSupplierWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'付款信息'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-add>
                <el-button @click="addPayDetail">添加付款信息</el-button>
              </template>
            </page-filter>
            <el-form
              ref="payDetailForm"
              :model="payDetailInfo"
              style="width: 100%"
            >
              <page-table
                v-model:data="payDetailInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="payDetailInfo.fieldList"
                :handle="payDetailInfo.handle"
              >
              </page-table>
            </el-form>
          </div>
        </div>

        <div v-if="formInfo.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'验收标准'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-add>
                <el-button @click="addAcceptanceDetail">添加验收项目</el-button>
              </template>
            </page-filter>
            <el-form
              ref="acceptanceDetailForm"
              :model="acceptanceDetailInfo"
              style="width: 100%"
            >
              <page-table
                v-model:data="acceptanceDetailInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="acceptanceDetailInfo.fieldList"
                :handle="acceptanceDetailInfo.handle"
              >
              </page-table>
            </el-form>
          </div>
        </div>

        <div v-if="formInfo.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-add>
                <el-button @click="addAsset">添加资产</el-button>
              </template>
              <template v-slot:filter-remove>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset"
                  >删除资产</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form
                ref="tableFormAsset"
                :model="tableInfo"
                style="width: 100%"
              >
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleAssetEvent"
                >
                  <template v-slot:col-assetApplicationNo="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetApplicationDetail(scope.row)"
                      >{{ scope.row.assetApplicationNo }}</span
                    >
                  </template>
                  <template v-slot:col-qty="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.qty`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positive,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        v-model.lazy="scope.row.qty"
                        style="width: 100%"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="scope.row.pendContractQty || 99999999"
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-price="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positiveMoneyAsset,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        v-model.lazy="scope.row.price"
                        style="width: 100%"
                        clearable
                        controls-position="right"
                        :precision="systemConfig.assets_price_precision"
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>

        <div v-else class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="productFilterInfo.list">
              <template v-slot:filter-add>
                <el-button @click="addProduct">添加产品</el-button>
              </template>
              <template v-slot:filter-remove>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form
                ref="tableForm"
                :model="productTableInfo"
                style="width: 100%"
              >
                <!-- 表格 -->
                <page-table
                  :refresh="productTableInfo.refresh"
                  :init-curpage="productTableInfo.initCurpage"
                  v-model:data="productTableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="productTableInfo.summaryFieldList"
                  :tab-index="true"
                  :query="productTableInfo.query"
                  :field-list="productTableInfo.fieldList"
                  :handle="productTableInfo.handle"
                  @handleEvent="handleProductEvent"
                >
                  <template v-slot:col-qty="scope">
                    <el-form-item class="margin-bottom">
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item ss">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positive,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="99999999"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item ww"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="scope.row.unitConvertCoefficient - 1"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                  <template v-slot:col-price="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positiveMoney,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        v-model.lazy="scope.row.price"
                        style="width: 100%"
                        clearable
                        controls-position="right"
                        :precision="systemConfig.price_precision"
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>附件信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.fileUrRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.filePathFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-filePathList>
                <UploadImgNew
                  v-model:value="formInfo.data.filePathList"
                  multiple
                  :action="action"
                  list-type="text"
                  title="合同附件"
                  :file-type="fileType"
                  :response-fn="handleResponse"
                />
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!--部门选择框-->
    <select-dept
      v-if="signDeptInfo.visible"
      v-model:show-dialog="signDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="signDeptInfo.query"
      :save-empty="true"
      @callback="selectSignDeptCallback"
    />
    <select-dept
      v-if="assetBelongDeptInfo.visible"
      v-model:show-dialog="assetBelongDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="assetBelongDeptInfo.query"
      :save-empty="true"
      @callback="selectAssetBelongDeptCallback"
    />
    <!--资产选择-->
    <select-equipment-archives
      v-if="selectEquipmentInfo.visible"
      v-model:show-dialog="selectEquipmentInfo.visible"
      :query="selectEquipmentInfo.query.queryMap"
      :query-params="selectEquipmentInfo.query.queryParams"
      :check-box="true"
      @callback="callBackEquipment"
    />
    <NewSelectProduct
      v-if="selectProductInfo.visible"
      v-model:show-dialog="selectProductInfo.visible"
      :query="selectProductInfo.query.queryMap"
      :query-params="selectProductInfo.query.queryParams"
      :api="selectProductInfo.api"
      :table-key="selectProductInfo.tableKey"
      :show-price="selectProductInfo.priceShow"
      @callback="selectProduct"
    />
    <!--资产申论选择-->
    <select-asset-application
      v-if="selectAssetApplicationInfo.visible"
      v-model:show-dialog="selectAssetApplicationInfo.visible"
      :query="selectAssetApplicationInfo.query.queryMap"
      :query-params="selectAssetApplicationInfo.query.queryParams"
      :check-box="false"
      :highlightRow="true"
      :save-empty="true"
      @callback="callBackAssetApplication"
    />
    <!-- 资产申论 -->
    <asset-application-detail
      v-if="assetApplicationDetailInfo.visible"
      :id="assetApplicationDetailInfo.id"
      v-model:visible="assetApplicationDetailInfo.visible"
      :title="assetApplicationDetailInfo.title"
    />
    <!-- 选择人员 -->
    <SelectUsers
      v-if="signUserInfo.visible"
      v-model:show-dialog="signUserInfo.visible"
      :query="signUserInfo.query"
      :api="signUserInfo.api"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSignUserCallback"
    />
    <select-supplier
      v-if="supplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      @callback="selectSupplierCallback"
    />
    <select-supplier
      v-if="winBiddingSupplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      v-model:show-dialog="winBiddingSupplierInfo.visible"
      :query="winBiddingSupplierInfo.query"
      @callback="selectWinBiddingSupplierCallback"
    />
    {{ sumAmount }}
  </div>
</template>
<script setup name="pendCheckContractModify">
import AssetApplicationDetail from '@/views/asset/assetManage/assetApplication/details'
import axios from 'axios'
import _ from 'lodash'
import { getRrgUserList } from '@/api/base.js'
import { getCustomizeSetting } from '@/api/customize'
import {
  getContractDetailCustomizeListAll,
  getContractProductDetailCustomizeListAll,
  createContract,
  updateContract,
  selectContractById,
  getContractPayDetailByOrderId,
  getContractAcceptanceDetailByOrderId,
} from '@/api/contract.js'
import utils from '@/common/js/utils'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const newSelectProduct = defineAsyncComponent(() =>
  import('@/components/NewSelectProduct/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'title', 'id'])

const formInfo = reactive({
  baseRef: null,
  repairRef: null,
  biddingRef: null,
  fileUrRef: null,
  data: {
    company: proxy.$store.state.user.userInfo.user.orgName || '',
    orgId: proxy.$store.state.user.userInfo.user.orgId || '',
    signDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    signDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    signUserName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    signUser: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.user.id
      : '',
    assetBelongDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    assetBelongDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    contactTel: proxy.$store.state.user.userInfo.user.tel
      ? proxy.$store.state.user.userInfo.user.tel
      : '',
  },
  fieldList: [
    {
      label: '合同类型',
      value: 'contractTypeValue',
      type: 'input',
      disabled: true,
    },
    {
      label: '合同名称',
      value: 'contractName',
      type: 'input',
    },
    {
      label: '公司名称',
      value: 'company',
      type: 'input',
      disabled: true,
    },
    {
      label: '开票方式',
      value: 'invoiceType',
      type: 'select-model',
      checkDefault: true,
      code: 'invoice_type',
    },
    {
      label: '金额',
      value: 'amount',
      type: 'number',
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      min: 0,
      max: 99999999,
    },
    {
      label: '签订人',
      value: 'signUserName',
      type: 'slot',
    },
    {
      label: '签订部门',
      value: 'signDeptName',
      type: 'slot',
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '签订日期',
      value: 'signDate',
      type: 'date',
    },
    {
      label: '验收日期',
      value: 'acceptanceDate',
      type: 'date',
    },
    {
      label: '要求到货日期',
      value: 'arrivalDate',
      type: 'date',
    },
    {
      label: '合同开始日期',
      value: 'contractStartDate',
      type: 'date',
    },
    {
      label: '合同结束日期',
      value: 'contractEndDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '总金额限制',
      value: 'sumAmountLimit',
      type: 'select-model',
      code: 'default_no_or_yes',
      show: false,
    },
    {
      label: '产品数量限制',
      value: 'qtyLimit',
      type: 'select-model',
      code: 'default_no_or_yes',
      show: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 100,
    },
  ],
  repairFieldList: [
    {
      label: '免费维保服务(年)',
      value: 'maintenanceYears',
      type: 'number',
      min: 0,
    },
    {
      label: '维保起算日期',
      value: 'maintenanceStartDate',
      type: 'date',
    },
    {
      label: '维保到期日期',
      value: 'maintenanceEndDate',
      type: 'date',
    },
  ],
  biddingFieldList: [
    {
      label: '招标日期',
      value: 'biddingDate',
      type: 'date',
    },
    {
      label: '招标文件编号',
      value: 'biddingFileNo',
      type: 'input',
    },
    {
      label: '招标方式',
      value: 'biddingType',
      type: 'select-model',
      checkDefault: true,
      code: 'bidding_type',
    },
    {
      label: '中标日期',
      value: 'winBiddingDate',
      type: 'date',
    },
    {
      label: '中标文件编号',
      value: 'winBiddingFileNo',
      type: 'input',
    },
    {
      label: '中标供应商',
      value: 'winBiddingSupplierName',
      type: 'slot',
    },
  ],
  filePathFieldList: [
    {
      label: '合同附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    contractName: [
      {
        required: true,
        message: '请输入合同名称',
        trigger: 'change',
      },
    ],
    invoiceType: [
      {
        required: true,
        message: '请选择开票方式',
        trigger: 'change',
      },
    ],
    amount: [
      {
        required: true,
        message: '请输入金额',
        trigger: 'blur',
      },
    ],

    signDate: [
      {
        required: true,
        message: '请选择签订日期',
        trigger: 'change',
      },
    ],
    acceptanceDate: [
      {
        required: true,
        message: '请选择验收日期',
        trigger: 'change',
      },
    ],
    contactTel: [
      {
        required: true,
        message: '请输入联系电话',
        trigger: 'change',
      },
      {
        validator: proxy.$validate.cellphone,
        trigger: 'change',
      },
    ],
    assetBelongDeptName: [
      {
        required: true,
        message: '请选择资产归口部门',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '135px',
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        asTbName: 'contract_detail',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        columnName: 'order_id',
        value: props.id,
      },
    },
    queryParams: {
      needPendContractQty: true,
    },
  },
  list: [
    {
      type: 'slot',
      value: 'add',
    },
    {
      type: 'slot',
      value: 'remove',
    },
  ],
})
const productFilterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        asTbName: 'contract_detail',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        columnName: 'order_id',
        value: props.id,
      },
    },
  },
  list: [
    {
      type: 'slot',
      value: 'add',
    },
    {
      type: 'slot',
      value: 'remove',
    },
  ],
})
const tableInfo = reactive({
  data: [],
  selections: [],
  fieldList: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '资产申论导入',
        event: addAssetApplication,
        show: true,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeAsset,
        show: true,
      },
    ],
  },
})
const productTableInfo = reactive({
  data: [],
  selections: [],
  fieldList: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
//选择产品相关
const selectProductInfo = reactive({
  visible: false,
  tableKey: 'contractAddProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {},
  },
  searchList: [],
})
const payDetailInfo = reactive({
  data: [],
  fieldList: [
    { label: '付款期', value: 'payPeriod', type: 'number' },
    { label: '付款比例(%)', value: 'payRate', type: 'number' },
    { label: '金额', value: 'payAmount', type: 'column', disabled: true },
    {
      label: '付款类型',
      value: 'payType',
      type: 'select-model',
      code: 'pay_type',
      rules: [
        {
          required: true,
          message: '付款类型',
          trigger: 'change',
        },
      ],
    },
    {
      label: '付款条件',
      value: 'payCondition',
      type: 'select-model',
      code: 'pay_condition',
      rules: [
        {
          required: true,
          message: '付款条件',
          trigger: 'change',
        },
      ],
    },
    { label: '付款日期', value: 'payDate', type: 'date' },
    {
      label: '付款状态',
      value: 'payStatus',
      type: 'select-model',
      code: 'pay_status',
      rules: [
        {
          required: true,
          message: '付款状态',
          trigger: 'change',
        },
      ],
    },
    {
      label: '支付方式',
      value: 'payWay',
      type: 'select-model',
      code: 'pay_way',
    },
    { label: '备注', value: 'remark', type: 'input' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: removePayDetail,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const acceptanceDetailInfo = reactive({
  data: [],
  fieldList: [
    { label: '验收项目', value: 'acceptanceItem', type: 'input' },
    {
      label: '验收标准/要求',
      value: 'acceptanceCriterion',
      type: 'input',
    },
    { label: '备注', value: 'remark', type: 'input' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: removeAcceptanceDetail,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const signDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
  },
})
const assetBelongDeptInfo = reactive({
  visible: false,
  query: {
    status: 1,
  },
})
const signUserInfo = reactive({
  //人员弹窗
  visible: false,
  saveEmpty: true,
  api: getRrgUserList,
  query: {},
})
const supplierInfo = reactive({
  visible: false,
  query: {},
})
const winBiddingSupplierInfo = reactive({
  visible: false,
  query: {},
})
const selectEquipmentInfo = reactive({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  },
})
const selectAssetApplicationInfo = reactive({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '6',
      },
    },
    queryParams: {
      productId: '',
    },
  },
})
const assetApplicationDetailInfo = reactive({
  visible: false,
  id: '',
  title: '申论详情',
})
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const fileType = ref(['docx', 'pdf', 'doc'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const index = ref('')
const formRefs = ref('')
const businessType = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canRemoveAsset = computed(() => {
  return tableInfo.selections.length
})
const canRemoveProduct = computed(() => {
  return productTableInfo.selections.length
})
const sumAmount = computed(() => {
  payDetailInfo.data.forEach((item) => {
    item.payAmount = parseFloat(
      utils.accMul(formInfo.data.amount || 0, item.payRate || 0) / 100
    ).toFixed(proxy.$store.state.permission.systemConfig.assets_price_precision)
  })
  return ''
})

watch(
  () => tableInfo.data,
  (data) => {
    if (data) {
      data.forEach((item) => {
        let sumAmount = proxy.$fn.accMul(
          item.qty || 0,
          parseFloat(item.price || 0)
        )
        item['sumAmount'] = sumAmount
      })
    }
  },
  {
    deep: true,
  }
)
watch(
  () => productTableInfo.data,
  (data) => {
    productTableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(calcQty, parseFloat(row.price)),
        unitConvertCoefficient
      )
    })
  },
  {
    deep: true,
  }
)

watch(
  () => formInfo.data.contractType,
  (value) => {
    if (parseInt(value) === 2) {
      showFieldListItem(false, 'acceptanceDate')
      showFieldListItem(false, 'arrivalDate')
      showFieldListItem(true, 'sumAmountLimit')
      showFieldListItem(true, 'qtyLimit')
    } else {
      showFieldListItem(true, 'acceptanceDate')
      showFieldListItem(true, 'arrivalDate')
      showFieldListItem(false, 'sumAmountLimit')
      showFieldListItem(false, 'qtyLimit')
    }
  }
)

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    componentType: 'number',
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    componentType: 'price',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
  assetApplicationNo: {
    label: '资产申购论证号',
    value: 'assetApplicationNo',
    type: 'slot',
    show: false,
    hidden: true,
  },
})

productTableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})

getCustomize()

function handleEventForm(event, val) {
  let rules = formInfo.rules
  if (event === 'contractType') {
    if (val === '1') {
      if (!rules.assetBelongDeptName) {
        rules.assetBelongDeptName = [
          {
            required: true,
            message: '请选择资产归口部门',
            trigger: 'change',
          },
        ]
      }
      showFieldListItem(true, 'businessType')
      showFieldListItem(true, 'assetBelongDeptName')
    } else if (val === '2') {
      if (rules.assetBelongDeptName) {
        delete rules.assetBelongDeptName
      }
      showFieldListItem(false, 'businessType')
      showFieldListItem(false, 'assetBelongDeptName')
    }
    tableInfo.data = []
    productTableInfo.data = []
    formInfo.data.assetBelongDeptName = ''
    formInfo.data.assetBelongDeptId = ''
    businessType.value = ''
    acceptanceDetailInfo.data = []
  }
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function addPayDetail() {
  let obj = {
    payPeriod: '',
    payRate: '',
    payAmount: '',
    payType: '',
    retentionType: '',
    payCondition: '',
    payDate: '',
    payStatus: '',
    payWay: '',
    remark: '',
  }
  payDetailInfo.data.push(obj)
}
function removePayDetail(row) {
  payDetailInfo.data = payDetailInfo.data.filter((item) => item !== row)
}
function addAcceptanceDetail(row, index) {
  acceptanceDetailInfo.data.splice(index + 1, 0, {
    acceptanceItem: '',
    acceptanceCriterion: '',
    remark: '',
  })
}
function removeAcceptanceDetail(row) {
  acceptanceDetailInfo.data = acceptanceDetailInfo.data.filter(
    (item) => item !== row
  )
}
function save() {
  if (formInfo.data.contractType == '1') {
    formRefs.value = [
      proxy.$refs['tableFormAsset'],
      proxy.$refs['acceptanceDetailForm'],
      proxy.$refs['payDetailForm'],
      formInfo.baseRef,
      formInfo.biddingRef,
      formInfo.repairRef,
      formInfo.fileUrRef,
    ]
  } else {
    formRefs.value = [
      proxy.$refs['tableForm'],
      proxy.$refs['acceptanceDetailForm'],
      proxy.$refs['payDetailForm'],
      formInfo.baseRef,
      formInfo.biddingRef,
      formInfo.repairRef,
      formInfo.fileUrRef,
    ]
  }
  if (formInfo.data.acceptanceDate <= formInfo.data.signDate) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '验收日期不能早于签订日期！',
    })
    return
  }
  if (formInfo.data.contractType == '1') {
    if (
      formInfo.data.maintenanceEndDate &&
      formInfo.data.maintenanceStartDate &&
      formInfo.data.maintenanceEndDate < formInfo.data.maintenanceStartDate
    ) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '维保到期日期不能早于维保起算日期！',
      })
      return
    }
  }
  let endDate = formInfo.data.contractEndDate
  let startDate = formInfo.data.contractStartDate
  if (endDate) {
    let fmartStartDate = new Date(startDate)
    let fmartEndDate = new Date(endDate)
    if (fmartEndDate.getTime() < fmartStartDate.getTime()) {
      proxy.$message({
        showClose: true,
        message: '合同结束日期不能大于合同开始日期',
        type: 'error',
        duration: 3500,
      })
      return
    }
  }
  if (tableInfo.data.length === 0 && formInfo.data.contractType == '1') {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '合同明细不能为空',
    })
    return
  } else if (
    productTableInfo.data.length === 0 &&
    formInfo.data.contractType == '2'
  ) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '合同明细不能为空',
    })
    return
  }
  let contractAmount = formInfo.data.amount
  let sumProductAmount = 0
  tableInfo.data.forEach((item) => {
    sumProductAmount = proxy.$fn.accAdd(
      sumProductAmount,
      proxy.$fn.accMul(item.qty || 0, item.price || 0)
    )
  })
  if (sumProductAmount > contractAmount) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '合同明细总金额不能大于合同金额!',
    })
    return
  }
  if (payDetailInfo.data.length > 0) {
    let sumAmount = 0
    let sumRate = 0
    payDetailInfo.data.forEach((item) => {
      sumAmount = proxy.$fn.accAdd(sumAmount, item.payAmount || 0)
      sumRate = proxy.$fn.accAdd(sumRate, item.payRate || 0)
    })
    if (sumRate > 100) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '付款总比例不能大于100%!',
      })
      return
    }
    if (sumAmount > contractAmount) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '付款总金额不能大于合同金额!',
      })
      return
    }
  }
  tableInfo.data.forEach((item) => {
    item.calcQty = item.qty
  })
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id ? updateContract : createContract
    let param = {
      ...formInfo.data,
      acceptanceDetailList: acceptanceDetailInfo.data,
      detailList: tableInfo.data,
      productDetailList: productTableInfo.data,
      payDetailList: payDetailInfo.data,
    }
    api(param).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify', false)
      }
    })
  })
}
function openDeptWindow() {
  //签订部门
  signDeptInfo.visible = true
}
function selectSignDeptCallback(row) {
  if (row && row.id) {
    formInfo.data['signDeptName'] = row.name
    formInfo.data['signDeptId'] = row.id
  }
}
function openAssetBelongDeptWindow() {
  //归口部门
  assetBelongDeptInfo.visible = true
}
function selectAssetBelongDeptCallback(row) {
  if (row && row.id) {
    formInfo.data['assetBelongDeptName'] = row.name
    formInfo.data['assetBelongDeptId'] = row.id
  }
}
function openSignUserWindow() {
  signUserInfo.query.deptId =
    formInfo.data.signDeptId === -2 ? '' : formInfo.data.signDeptId
  //签订人
  signUserInfo.visible = true
}
function selectSignUserCallback(row) {
  if (row && row.id) {
    formInfo.data['signUserName'] = row.name
    formInfo.data['signUser'] = row.id
  }
}
function openSupplierWindow() {
  //供应商
  supplierInfo.visible = true
}
function selectSupplierCallback(row) {
  if (row && row.supplierId) {
    formInfo.data['supplierName'] = row.supplierName
    formInfo.data['supplierId'] = row.supplierId
  }
}
function openwinBiddingSupplierWindow() {
  //中标供应商
  winBiddingSupplierInfo.visible = true
}
function selectWinBiddingSupplierCallback(row) {
  if (row && row.supplierId) {
    formInfo.data['winBiddingSupplierName'] = row.supplierName
    formInfo.data['winBiddingSupplierId'] = row.supplierId
  }
}
function addAsset() {
  if (tableInfo.data.length) {
    selectEquipmentInfo.query.queryMap.id.value = tableInfo.data
      .map((item) => item.productId)
      .toString()
  } else {
    selectEquipmentInfo.query.queryMap.id.value = ''
  }
  selectEquipmentInfo.visible = true
}
function addAssetApplication(row, _index) {
  index.value = _index
  if (tableInfo.data && tableInfo.data.length > 0) {
    selectAssetApplicationInfo.query.queryMap.id.value = tableInfo.data
      .map((item) => item.assetApplicationId)
      .toString()
  } else {
    selectAssetApplicationInfo.query.queryMap.id.value = ''
  }
  if (props.id) {
    selectAssetApplicationInfo.query.queryParams.contractId = props.id
  }
  selectAssetApplicationInfo.query.queryParams.productId = row.productId
  selectAssetApplicationInfo.visible = true
}
//选择产品
function addProduct() {
  const productIds = productTableInfo.data.map((item) => item.productId)
  selectProductInfo.query.queryMap.id.value = productIds.toString()
  selectProductInfo.visible = true
}
function selectProduct(rows = []) {
  if (rows && rows.length) {
    rows = rows.map((row) => {
      return {
        ...row,
        price: row.price,
        largeUnitQty: 0,
        qty: 1,
        code: null,
        productionDate: undefined,
        validityDate: undefined,
        productId: row.id,
        rowId: proxy.$fn.getUid(),
        id: null,
        preProductName: row.commonName,
        preProductCode: row.code,
        factoryMainCode: row.mainCode,
        factorySubCode: row.subCode,
        defaultSupplierId: row.supplierId,
        defaultSupplierName: row.supplierName,
        defaultSupplierCode: row.supplierCode,
        defaultSupplierPrice: row.price,
      }
    })
    productTableInfo.data = rows.concat(productTableInfo.data)
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    productTableInfo.data = productTableInfo.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        productTableInfo.data = productTableInfo.data.filter(
          (row) => !productTableInfo.selections.includes(row)
        )
      })
  }
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
function largeMax(row) {
  //原厂码最大为1[0,1]
  if (row.codeType === 3) {
    return 1
  } else {
    return 99999999
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}
// 触发事件
function handleAssetEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
// 触发事件
function handleProductEvent(event, data) {
  const tableInfo = productTableInfo
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function removeAsset(row = undefined) {
  if (row.id && row) {
    tableInfo.data = tableInfo.data.filter((item) => row !== item)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function callBackEquipment(rows) {
  if (rows && rows.length) {
    const data = rows.map(function (row) {
      return {
        id: row.id,
        productId: row.id,
        commonName: row.commonName,
        productCode: row.code,
        standard: row.standard,
        trademark: row.trademark,
        brandName: row.brandName,
        unitName: row.unitName,
        deviceTypeValue: row.deviceTypeValue,
        preProductName: row.commonName,
        preProductCode: row.code,
        preStandard: row.standard,
        preTrademark: row.trademark,
        preBrandName: row.brandName,
        preDeviceTypeValue: row.deviceTypeValue,
        pendContractQty: undefined,
        qty: undefined,
        price: row.price,
      }
    })
    tableInfo.data = data.concat(tableInfo.data)
  }
}
function callBackAssetApplication(data) {
  if (data && data.id) {
    tableInfo.data[index.value] = {
      ...tableInfo.data[index.value],
      assetApplicationId: data.id,
      assetApplicationNo: data.orderNo,
      qty: data.qty,
      price: data.price,
      pendContractQty: data.qty - data.preContractQty,
    }
  } else {
    tableInfo.data[index.value] = {
      ...tableInfo.data[index.value],
      assetApplicationId: -2,
      assetApplicationNo: '',
      pendContractQty: undefined,
    }
  }
}
function showAssetApplicationDetail(row) {
  assetApplicationDetailInfo.id = row.assetApplicationId
  assetApplicationDetailInfo.visible = true
}
function getMain() {
  selectContractById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data

      getList()
    }
  })
}
function getList() {
  let params = {
    orderId: props.id,
  }
  if (formInfo.data.contractType == '1') {
    showFieldListItem(true, 'assetBelongDeptName')
    getContractDetailCustomizeListAll(filterInfo.query).then((res) => {
      if (res && res.success) {
        tableInfo.data = res.data
      }
    })
    getContractAcceptanceDetailByOrderId(params).then((resp) => {
      if (resp && resp.success) {
        acceptanceDetailInfo.data = resp.data
      }
    })
  } else {
    showFieldListItem(false, 'assetBelongDeptName')
    getContractProductDetailCustomizeListAll(productFilterInfo.query).then(
      (res) => {
        if (res && res.success) {
          productTableInfo.data = res.data
        }
      }
    )
  }
  getContractPayDetailByOrderId(params).then((resp) => {
    if (resp && resp.success) {
      payDetailInfo.data = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'contractAssetModify-com.slip.spd.entity.vo.contract.ContractDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      //请求耗材的自定义配置
      let productParam = {
        tableKey:
          'contractProductModify-com.slip.spd.entity.vo.contract.ContractProductDetailVO',
      }

      getCustomizeSetting(productParam).then((res) => {
        if (res && res.success) {
          let data = res.data
          productFilterInfo.query.customizeUserVO = data
          let obj = proxy.$fn.setFieldList(
            productTableInfo.fieldList,
            data.detail,
            true
          )
          productTableInfo.fieldList = obj.fieldList
          if (props.id) {
            getMain()
          }
        }
      })
    }
  })
}
function handleResponse(response, file) {
  return file
}
</script>
